package com.edgclub.edg.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.android.volley.VolleyError;
import com.edgclub.edg.R;
import com.edgclub.edg.activity.BannerComponent;
import com.edgclub.edg.activity.EDGStarComponent;
import com.edgclub.edg.activity.GroupDetailsActivity;
import com.edgclub.edg.activity.GzTopicDetailActivity;
import com.edgclub.edg.activity.GzWebViewActivity;
import com.edgclub.edg.adapter.FindEntranceAdapter;
import com.edgclub.edg.adapter.FindIndexAdapter;
import com.edgclub.edg.adapter.adapteruitls.MyItemClickListener;
import com.edgclub.edg.api.FindApi;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.param.PostsParam;
import com.edgclub.edg.constant.BBConstant;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.model.Banner;
import com.edgclub.edg.model.RecommendTopic;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.FindIndexData;
import com.edgclub.edg.uc.UnableScrollGridView;
import com.edgclub.edg.uc.autoscrollviewpager.AutoScrollViewPager;
import com.edgclub.edg.utils.GlideUtil.GlideUtils;
import com.edgclub.edg.utils.util.DensityUtils;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.squareup.otto.ThreadEnforcer;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;

public class FindIndexFragment extends GzBaseFragment {

    private Activity mActivity;

    private int currPage = 1;
    private int pageSize = 20;
    private XRecyclerView recyclerView;
    private FindIndexAdapter findIndexAdapter;
    private ArrayList<RecommendTopic> detailDatas;
    private View headView;
    private int spacingInPixels;

    private UserPrefUtils userPrefUtils;
    private FindApi findApi;
    private GlideUtils glideUtils;

    //头部
    private ImageView imgv_ad1,imgv_ad2,imgv_ad3;
    private FrameLayout ll_banner;
    private LinearLayout ll_star;
    private ViewPager star_viewpager;//EDG之星
    private LinearLayout viewGroup_star;
    private AutoScrollViewPager banner_viewPager;
    private LinearLayout viewGroup;
    private UnableScrollGridView unableScrollGridView;
    private FindEntranceAdapter entranceAdapter;
    private ArrayList<FindIndexData.Entrance> entrances;
    private BannerComponent bannerCommon;
    private EDGStarComponent starComponent;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mActivity = this.getActivity();
        return inflater.inflate(R.layout.fragment_find_index, container, false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).register(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initData();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
//        if(isVisibleToUser){
//            if(bannerCommon!=null){
////                bannerCommon.s
//            }
//        }else{
//            if(bannerCommon!=null){
//                bannerCommon.stopAutoScroll();
//            }
//        }
    }

    private void initView(View view) {
        initLoadView(view);

        spacingInPixels = DensityUtils.dip2px(mActivity,7);
        recyclerView = (XRecyclerView) view.findViewById(R.id.recyclerview);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        headView =   LayoutInflater.from(mActivity).inflate(R.layout.head_find_index, (ViewGroup)mActivity.findViewById(android.R.id.content),false);
        initHeadView(headView);
        recyclerView.addHeaderView(headView);
//        recyclerView.addItemDecoration(new SpaceItemDecoration2(mActivity));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int pos = parent.getChildAdapterPosition(view);
                if(pos == 1)return;
//
                outRect.left = spacingInPixels;
                outRect.right = spacingInPixels;


//                if (pos%2!=0) {
//                    outRect.left = 0;
//                    outRect.right = spacingInPixels;
//                } else {
//                    outRect.left = spacingInPixels;
//                    outRect.right = 0;
//                }
            }
        });
        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                currPage = 1;
                getIndex(currPage);
            }

            @Override
            public void onLoadMore() {
                getIndex(currPage);
            }
        });


    }

    private void initData() {
        findApi = new FindApi(getActivity());
        userPrefUtils = new UserPrefUtils(getActivity());
        detailDatas = new ArrayList<>();
        glideUtils = new GlideUtils();
        bannerCommon = new BannerComponent();
        starComponent = new EDGStarComponent();

        bannerCommon.init(mActivity,banner_viewPager,viewGroup);

        findIndexAdapter = new FindIndexAdapter(getActivity());
        findIndexAdapter.setDetailDatas(detailDatas);
        recyclerView.setAdapter(findIndexAdapter);

        getIndex(currPage);
        findIndexAdapter.setOnItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int postion) {
                findIndexAdapter.jumpTopicDetailActivity(postion);
            }
        });

    }

    private boolean edgLoading = false;
    private boolean isEdgEnd = false;

    private void getIndex(int page) {
        if (edgLoading || isEdgEnd) {
            return;
        }
        User user = userPrefUtils.getUser();
        PostsParam nearbyParam = new PostsParam();
        nearbyParam.setPage(page + "");
        nearbyParam.setPageSize(pageSize + "");
        nearbyParam.setUserId(user.getId() + "");
        findApi.index(nearbyParam, new getIndexListener());//关注列表
    }


    class getIndexListener implements VolleyListener {

        @Override
        public void onStart(String tag) {
            edgLoading = true;
        }

        @Override
        public void onSuccess(String response, String tag) {
            edgLoading = false;
            recyclerView.refreshComplete();
            recyclerView.loadMoreComplete();
            setLoadViewGONE();
            if (JSONHelper.isSuccess(response)) {
                FindIndexData data = JsonUtil.getMode(response, FindIndexData.class);
                if(currPage==1){
                    setBanner(data.getData().getBanners());
                    setStar(data.getData().getStars());
                    setAds(data.getData().getAds());
                    setEntrance(data.getData().getEntrances());
                }

                ArrayList<RecommendTopic> topics = data.getData().getPosts();
                if (topics != null && topics.size() > 0) {
                    if (currPage == 1) {
                        detailDatas.clear();
                    }
                    detailDatas.addAll(topics);
                    currPage++;
                    findIndexAdapter.notifyDataSetChanged();
                }else{
                    recyclerView.noMoreLoading();
                }
            } else {

            }

        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
            edgLoading = false;
            recyclerView.refreshComplete();
            recyclerView.loadMoreComplete();
            setNoNetWork(new ReLoadClickListener() {
                @Override
                public void reload() {
                    getIndex(currPage);
                }
            });
            ResultCode.toastVolleyError(getActivity(), volleyError);
        }
    }


    private void initHeadView(View view){
        imgv_ad1 = (ImageView) view.findViewById(R.id.imgv_ad1);
        imgv_ad2 = (ImageView) view.findViewById(R.id.imgv_ad2);
        imgv_ad3 = (ImageView) view.findViewById(R.id.imgv_ad3);
        ll_banner = (FrameLayout) view.findViewById(R.id.ll_banner);
        ll_star = (LinearLayout) view.findViewById(R.id.ll_star);
        banner_viewPager = (AutoScrollViewPager) view.findViewById(R.id.view_pager);
        star_viewpager = (ViewPager) view.findViewById(R.id.star_viewpager);
        viewGroup = (LinearLayout) view.findViewById(R.id.viewGroup);
        viewGroup_star = (LinearLayout) view.findViewById(R.id.viewGroup_star);
        unableScrollGridView = (UnableScrollGridView) view.findViewById(R.id.unableScrollGridView);
        entranceAdapter = new FindEntranceAdapter(mActivity);
        entrances = new ArrayList<>();
        entranceAdapter.setEntrances(entrances);
        unableScrollGridView.setAdapter(entranceAdapter);

    }

    /**
     * banner
     * @param banners
     */
    private void setBanner(ArrayList<Banner> banners){
        if(banners!=null && banners.size()>0){
            ll_banner.setVisibility(View.VISIBLE);
            bannerCommon.setBanners(banners);
        }else{
            ll_banner.setVisibility(View.GONE);
        }
    }

    /**
     * 广告
     * @param ads
     */
    private void setAds(final ArrayList<Banner> ads){
        if(ads==null)return;
        imgv_ad1.setVisibility(View.INVISIBLE);
        imgv_ad2.setVisibility(View.INVISIBLE);
        imgv_ad3.setVisibility(View.INVISIBLE);
        for(int i=0;i<ads.size();i++){
            if(i == 0){
                imgv_ad1.setVisibility(View.VISIBLE);
                glideUtils.Glidde_loadImage(mActivity,ads.get(i).getImgUrl(),imgv_ad1);
                imgv_ad1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        jupAct(ads.get(0));
                        //统计点击事件
                        HashMap<String,String> map = new HashMap<String,String>();
                        map.put("tid",ads.get(0).getId());
                        map.put("title",ads.get(0).getTitle());
                        MobclickAgent.onEvent(getActivity(), "EC_FIND_AD", map);
                    }
                });
            }
            if(i==1){
                imgv_ad2.setVisibility(View.VISIBLE);
                glideUtils.Glidde_loadImage(mActivity,ads.get(i).getImgUrl(),imgv_ad2);
                imgv_ad2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        jupAct(ads.get(1));
                        //统计点击事件
                        HashMap<String,String> map = new HashMap<String,String>();
                        map.put("tid",ads.get(1).getId());
                        map.put("title",ads.get(1).getTitle());
                        MobclickAgent.onEvent(getActivity(), "EC_FIND_AD", map);
                    }
                });
            }
            if(i==2){
                imgv_ad3.setVisibility(View.VISIBLE);
                glideUtils.Glidde_loadImage(mActivity,ads.get(i).getImgUrl(),imgv_ad3);
                imgv_ad3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        jupAct(ads.get(2));
                        //统计点击事件
                        HashMap<String,String> map = new HashMap<String,String>();
                        map.put("tid",ads.get(2).getId());
                        map.put("title",ads.get(2).getTitle());
                        MobclickAgent.onEvent(getActivity(), "EC_FIND_AD", map);
                    }
                });
            }
        }
    }

    private void jupAct(Banner banner) {
        try {
            String protocol = banner.getProtocol();
            String msg = protocol.substring(protocol.indexOf("//")+2);
            String key = msg.substring(0,msg.indexOf("/"));
            String value = msg.substring(msg.indexOf("/")+1);

            if(key.equals(BBConstant.BANNER_JUMP_TYPE_URL)){
                Intent i = new Intent(mActivity,GzWebViewActivity.class);
                i.putExtra("url", value);
                i.putExtra("title", banner.getTitle());
                mActivity.startActivity(i);
            }else if(key.equals(BBConstant.BANNER_JUMP_TYPE_BB)){
                Intent intent = new Intent(mActivity,GzTopicDetailActivity.class);
                intent.putExtra("topicId", value);
                mActivity.startActivity(intent);

            }else if(protocol.contains(BBConstant.BANNER_JUMP_TYPE_TAOBAO1) || protocol.contains(BBConstant.BANNER_JUMP_TYPE_TAOBAO2)){
                //跳转商城
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.JUMPTAOBAO);
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                        ThreadEnforcer.MAIN).post(hashMap);

            }else if(key.equals( BBConstant.BANNER_JUMP_TYPE_GROUP)){
                Intent intent=new Intent(mActivity, GroupDetailsActivity.class);
                intent.putExtra("groupid",value);
                intent.putExtra("groupname","群组");
                mActivity.startActivity(intent);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    /**
     * 活动入口
     */
    private void setEntrance(ArrayList<FindIndexData.Entrance> es){
        if(es!=null && es.size()>0){
            entrances.clear();
            unableScrollGridView.setVisibility(View.VISIBLE);
            entrances.addAll(es);
            entranceAdapter.notifyDataSetChanged();
        }else{
            unableScrollGridView.setVisibility(View.GONE);
        }
        unableScrollGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });
    }

    /**
     * EDG之星
     * @param stars
     */
    private void setStar(ArrayList<User> stars){
        if(stars!=null && stars.size()>0){
            ll_star.setVisibility(View.VISIBLE);
            starComponent.init(mActivity,star_viewpager,viewGroup_star,this.getChildFragmentManager(),stars);
        }else{
            ll_star.setVisibility(View.GONE);
        }

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).unregister(this);
    }

}
